package ink.xiaobaibai.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.annotation.InsidePublicResources;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.controller.onePay.OzoneDeviceController;
import ink.xiaobaibai.entity.*;
import ink.xiaobaibai.enumOxy.DeviceStatus;
import ink.xiaobaibai.enumOxy.FaultStatus;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.*;
import ink.xiaobaibai.units.MySecurity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 受理故障
 * @author: 小白白
 * @create: 2021-06-03
 **/

@RestController
@RequestMapping("/fault")
@CrossOrigin
@Api(tags = "受理故障接口")
@InsidePublicResources
public class FaultDeviceController {

    @Autowired
    private IFaultDeviceService faultDeviceService;

    @Autowired
    private IFaultTerminalService faultTerminalService;

    @Autowired
    private IOzoneDeviceService ozoneDeviceService;

    @Autowired
    private IOxygenDeviceService oxygenDeviceService;

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private OzoneDeviceController deviceController;

    /**
     * 查看所有用户提交故障
     */
    @GetMapping("/user/all-list")
    @ApiOperation("查看用户提交故障")
    public ResponseFormat allUserList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<FaultDevice> q1 = new QueryWrapper<>();
        if (!MySecurity.isPower(MyRole.POWER_ONE)) {
            String role = MySecurity.getRole();
            if (role.equals(MyRole.DISTRIBUTOR)) {
                q1.eq("admin_user_id", userId);
            } else if (role.equals(MyRole.AGENT)) {
                q1.eq("dep_id", this.adminUserService.getDepId(userId));
            }
        }
        q1.orderByDesc("id");
        Page<FaultDevice> page = this.faultDeviceService.page(new Page<>(pageNum, pageSize), q1);
        return ResponseFormat.success(page);
    }

    @GetMapping("/user/item/{id}")
    @ApiOperation("查看用户故障详细")
    public ResponseFormat getFaultUserItem(@PathVariable Integer id) {
        FaultDevice faultDevice = this.faultDeviceService.getById(id);
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.select("id", "user_phone", "user_name", "department_id");
        q1.eq("id", id);
        AdminUser adminUser = this.adminUserService.getOne(q1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("adminUser", adminUser);
        jsonObject.put("faultDevice", faultDevice);
        return ResponseFormat.success(jsonObject);
    }

    @PostMapping("/user/ok/{id}")
    @ApiOperation("处理当前用户提交的故障")
    public ResponseFormat okFaultUserItem(@PathVariable("id") Integer id) {
        Integer userId = MySecurity.getUserId();
        String role = MySecurity.getRole();
        FaultDevice faultDevice = this.faultDeviceService.getById(id);

        if (!MySecurity.isPower(MyRole.POWER_ONE)) {
            if (role.equals(MyRole.DISTRIBUTOR)) {
                if (!userId.equals(faultDevice.getAdminUserId())) {
                    return ResponseFormat.fail("权限不足");
                }
            } else if (role.equals(MyRole.AGENT)) {
                if (!this.adminUserService.getDepId(userId).equals(faultDevice.getDepId())) {
                    return ResponseFormat.fail("权限不足");
                }
            }
        }

        faultDevice.setStatus(FaultStatus.PROCESSED.getStatus());
        this.faultDeviceService.updateById(faultDevice);
        return ResponseFormat.success();
    }

    @GetMapping("/terminal/one/all-list")
    @ApiOperation("查看终端提交的所有故障(定点)")
    public ResponseFormat allDeviceListOne(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        QueryWrapper<FaultTerminal> q1 = new QueryWrapper<>();
        this.q(q1);
        q1.likeRight("message", "定点");
        Page<FaultTerminal> page = this.faultTerminalService.page(new Page<>(pageNum, pageSize), q1);
        return ResponseFormat.success(page);
    }

    @GetMapping("/terminal/mon/all-list")
    @ApiOperation("查看终端提交的所有故障(月费)")
    public ResponseFormat allDeviceListMon(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        QueryWrapper<FaultTerminal> q1 = new QueryWrapper<>();
        this.q(q1);
        q1.likeRight("message", "月费");
        Page<FaultTerminal> page = this.faultTerminalService.page(new Page<>(pageNum, pageSize), q1);
        return ResponseFormat.success(page);
    }

    @GetMapping("/terminal/buy/all-list")
    @ApiOperation("查看终端提交的所有故障(购买)")
    public ResponseFormat allDeviceListBuy(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        QueryWrapper<FaultTerminal> q1 = new QueryWrapper<>();
        this.q(q1);
        q1.likeRight("message", "购买");
        Page<FaultTerminal> page = this.faultTerminalService.page(new Page<>(pageNum, pageSize), q1);
        return ResponseFormat.success(page);
    }

    @GetMapping("/terminal/free/all-list")
    @ApiOperation("查看终端提交的所有故障(酒店)")
    public ResponseFormat allDeviceListFree(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize) {
        QueryWrapper<FaultTerminal> q1 = new QueryWrapper<>();
        this.q(q1);
        q1.likeRight("message", "酒店");
        Page<FaultTerminal> page = this.faultTerminalService.page(new Page<>(pageNum, pageSize), q1);
        return ResponseFormat.success(page);
    }

    private void q(QueryWrapper<FaultTerminal> q1) {
        if (!MySecurity.getRoles().contains(MyRole.POWER_ONE)) {
            String role = MySecurity.getRole();
            Integer userId = MySecurity.getUserId();
            if (role.equals(MyRole.DISTRIBUTOR)) {
                q1.eq("admin_user_id", userId);
            }
            if (role.equals(MyRole.AGENT)) {
                q1.eq("dep_id", this.adminUserService.getDepId(userId));
            }
        }
        q1.orderByDesc("create_time");
    }

    @GetMapping("/terminal/item/{id}")
    @ApiOperation("查看终端故障详细")
    public ResponseFormat getFaultTerminalItem(@PathVariable Integer id) {
        FaultTerminal faultTerminal = this.faultTerminalService.getById(id);
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.select("user_name", "user_phone");
        q1.eq("id", faultTerminal.getAdminUserId());
        AdminUser adminUser = this.adminUserService.getOne(q1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("adminUser", adminUser);
        jsonObject.put("faultTerminal", faultTerminal);
        return ResponseFormat.success(jsonObject);
    }

    @PostMapping("/terminal/ok/{id}")
    @ApiOperation("处理当前终端故障")
    public ResponseFormat okFaultTerminalItem(@PathVariable Integer id) {
        Integer userId = MySecurity.getUserId();
        String role = MySecurity.getRole();
        FaultTerminal faultTerminal = this.faultTerminalService.getById(id);

        if (faultTerminal.getMessage().startsWith("定点")) {

            if (!MySecurity.isPower(MyRole.POWER_ONE)) {
                if (role.equals(MyRole.DISTRIBUTOR) && !faultTerminal.getAdminUserId().equals(userId)) {
                    return ResponseFormat.fail("权限不足");
                }
                if (role.equals(MyRole.AGENT) && !faultTerminal.getDepId().equals(this.adminUserService.getDepId(userId))) {
                    return ResponseFormat.fail("权限不足");
                }
            }

        } else if (faultTerminal.getMessage().startsWith("月费")) {

            if (!MySecurity.isPower(MyRole.POWER_MONTHLY)) {
                if (role.equals(MyRole.DISTRIBUTOR) && !faultTerminal.getAdminUserId().equals(userId)) {
                    return ResponseFormat.fail("权限不足");
                }
                if (role.equals(MyRole.AGENT) && !faultTerminal.getDepId().equals(this.adminUserService.getDepId(userId))) {
                    return ResponseFormat.fail("权限不足");
                }
            }

        } else if (faultTerminal.getMessage().startsWith("购买")) {

            if (!MySecurity.isPower(MyRole.POWER_BUY)) {
                if (role.equals(MyRole.DISTRIBUTOR) && !faultTerminal.getAdminUserId().equals(userId)) {
                    return ResponseFormat.fail("权限不足");
                }
                if (role.equals(MyRole.AGENT) && !faultTerminal.getDepId().equals(this.adminUserService.getDepId(userId))) {
                    return ResponseFormat.fail("权限不足");
                }
            }

        } else {

            if (!MySecurity.isPower(MyRole.POWER_FREE)) {
                if (role.equals(MyRole.DISTRIBUTOR) && !faultTerminal.getAdminUserId().equals(userId)) {
                    return ResponseFormat.fail("权限不足");
                }
                if (role.equals(MyRole.AGENT) && !faultTerminal.getDepId().equals(this.adminUserService.getDepId(userId))) {
                    return ResponseFormat.fail("权限不足");
                }
            }

        }

        String deviceCode = faultTerminal.getDeviceCode();
        faultTerminal.setStatus(FaultStatus.PROCESSED.getStatus());
        // 只关心定点的
        if (faultTerminal.getMessage().contains("定点")) {
            if (faultTerminal.getMessage().contains("臭氧")) {
                QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
                q1.select("id");
                q1.eq("device_code", deviceCode);
                ResponseFormat responseFormat = this.deviceController.okFaultOrStop(this.ozoneDeviceService.getOne(q1).getId());
                if (responseFormat.getCode() == 1) {
                    this.faultTerminalService.updateById(faultTerminal);
                    responseFormat.setMsg(responseFormat.getMsg() + ";故障已清除");
                    return responseFormat;
                }
            } else {
                //氧气的
                QueryWrapper<OxygenDevice> q1 = new QueryWrapper<>();
                q1.select("id");
                q1.eq("device_code", deviceCode);
                this.oxygenDeviceService.updateDeviceStatus(this.oxygenDeviceService.getOne(q1).getId(), DeviceStatus.FREE);
            }
        }
        this.faultTerminalService.updateById(faultTerminal);
        return ResponseFormat.success();
    }

}
